package com.glacier.common.support.service.impl;

import com.glacier.common.core.domain.TreeEntity;
import com.glacier.common.core.mapper.TreeMapper;
import com.glacier.common.core.service.TreeService;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * date 2022-12-30 10:43
 *
 * @author glacier
 * @version 1.0
 */
public abstract class TreeServiceImpl<Mapper extends TreeMapper<T>,
    T extends TreeEntity<T>> extends BaseServiceImpl<Mapper, T> implements TreeService<T> {

    protected TreeServiceImpl(Class<Mapper> clz) {
        super(clz);
    }

    /**
     * 删除
     *
     * @param entity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int delete(T entity) {
        return this.batchDelete(List.of(entity.getId()));
    }

    /**
     * 删除
     * @param idList
     * @return
     * @param <ID>
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public <ID extends Serializable> int batchDelete(List<ID> idList) {
        if (idList.isEmpty()) {
            return 0;
        }
        // 获取删除节点的所有子节点(包含自身)
        List<ID> allDeletedIds = mapper.findAllChildrenIds(idList);
        int delete = super.batchDelete(allDeletedIds);
        // 回调
        afterBatchDelete(allDeletedIds);
        return delete;
    }

    /**
     * 删除回调
     *
     * @param deleted
     * @param <ID>
     */
    protected <ID extends Serializable> void afterBatchDelete(final List<ID> deleted) {

    }
}
